<template>
    <div class="budget-bar-chart" ref="barChartBox">
    </div>
</template>

<script setup lang="ts">
import * as echarts from 'echarts'
import {ref,computed, onMounted,onUnmounted,watch} from 'vue'
const props = defineProps({
    barChartData:{
        default:{
            type: ['Profit', 'Expenses', 'Income'],
            income: [320, 302, 341, 374, 390, 450, 420],
            expenses: [-120, -132, -101, -134, -190, -230, -210],
            date: [1,2,3,4,5,6,7]
        }
    }
})

let barChartBox = ref<HTMLElement>()
let profit = computed(() => {
    return props.barChartData.income.map((item:any, index:any) => {
        return item + props.barChartData.expenses[index]
    })
})
const updateBarChart = ()=>{
    console.log(props.barChartData);
    barOption.xAxis[0].data = props.barChartData.date
    barOption.series[0].data = profit.value
    barOption.series[1].data = props.barChartData.income
    barOption.series[2].data = props.barChartData.expenses
    barChart.setOption(barOption)
}
// 获取数据后，进行柱状图的更新
watch(() => props.barChartData.expenses, updateBarChart)

let barOption = {
    tooltip: {
        trigger: 'axis',
        axisPointer: {
            type: 'shadow'
        }
    },
    title: {
        text: '每日收支概况',
        left: '40%'
    },
    legend: {
        data: props.barChartData.type
    },
    grid: {
        left: '3%',
        right: '4%',
        bottom: '3%',
        containLabel: true
    },
    yAxis: [
        {
            type: 'value'
        }
    ],
    xAxis: [
        {
            type: 'category',
            axisTick: {
                show: false
            },
            data: props.barChartData.date
        }
    ],
    series: [
        {
            name: '净收入',
            type: 'bar',
            label: {
                // show: true,
                position: 'inside'
            },
            emphasis: {
                focus: 'series'
            },
            data: profit.value
        },
        {
            name: '收入',
            type: 'bar',
            stack: 'Total',
            emphasis: {
                focus: 'series'
            },
            data: props.barChartData.income
        },
        {
            name: '支出',
            type: 'bar',
            stack: 'Total',
            emphasis: {
                focus: 'series'
            },
            data: props.barChartData.expenses
        }
    ]
}

let barChart:any = null


onMounted(()=>{
    barChart = echarts.init(barChartBox.value)
    updateBarChart()
})

</script>
<style scoped>
.budget-bar-chart {
    width: 100%;
    height: 90%;
}
</style>